package com.fone.player.sns.impl;

import java.util.HashMap;

import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.Platform.ShareParams;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.PlatformDb;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qzone.QZone;
import cn.sharesdk.tencent.weibo.TencentWeibo;

import com.fone.player.ApplicationManage;
import com.fone.player.sns.ISNSShareManager;
import com.fone.player.sns.bean.SNSUserInfo;
import com.fone.player.sns.bean.ShareInfo;
import com.fone.player.sns.util.SNSUtil;
import com.fone.player.sns.util.WeiXinShareUtil;
import com.fone.player.sns.view.MyAuthorizeAdapter;
import com.fone.player.sns.view.MyQZoneWebShareAdapter;
import com.fone.player.util.FoneUtil;
import com.fone.player.util.L;
import com.fone.player.util.SerializationUtil;

public class SNSShareManager implements ISNSShareManager {
	
	private static final String TAG = "SNSShareManager";
	
	private static final int GET_USERINFO_SUCCESS = 5;
	private static final int STOP_SNS = 6;
	private boolean SNSPageOpening = false;
	
	private static Context mContext;
	private ShareStateListener mShareStateListener;
	
	private Handler mHandler;
	
	private ShareInfo tempInfo;
	
	private static SNSShareManager mSNSShareManager;
	
	public SNSUserInfo sinaLocalInfo = null;
	public SNSUserInfo tencentLocalInfo = null;
	
	private SNSShareManager(Context context){
		mContext = context;
		iniHandler();
	}
	
	public static void iniSNSShareManager(Context context){
		mContext = context;
		if(mSNSShareManager==null){
			mSNSShareManager = new SNSShareManager(context);
			mSNSShareManager.sinaLocalInfo = SerializationUtil.readSNSInfoSerialization(mContext, SINA_WEIBO_LOCALSNSINFO);
			mSNSShareManager.tencentLocalInfo = SerializationUtil.readSNSInfoSerialization(mContext, TENCENT_WEIBO_LOCALSNSINFO);
		}
	}
	
	public static SNSShareManager getInstance(){
		if(mSNSShareManager==null){
			throw new IllegalStateException(" SNSShareManager has not been initialized ");
		}
		return mSNSShareManager;
	}
	
	@SuppressLint("HandlerLeak")
	private void iniHandler(){
		   mHandler = new Handler(mContext.getMainLooper()){
			   
				@Override
				public void handleMessage(Message msg) {
					switch (msg.what) {
					case  ShareStateListener.SHARING:
						mShareStateListener.shareAction(ShareStateListener.SHARING, (String)msg.obj);
						break;
					case  ShareStateListener.SHARE_SUCCESS:
						mShareStateListener.shareAction(ShareStateListener.SHARE_SUCCESS, (String)msg.obj);
						break;
					case  ShareStateListener.SHARE_CANCEL:
						mShareStateListener.shareAction(ShareStateListener.SHARE_CANCEL, (String)msg.obj);
						break;
					case  ShareStateListener.SHARE_FAILED:
						mShareStateListener.shareAction(ShareStateListener.SHARE_FAILED, (String)msg.obj);
						break;
					case  GET_USERINFO_SUCCESS:
						mShareStateListener.onUserInfoComplete((SNSUserInfo)(msg.obj));
						break;
					case  STOP_SNS:
						if((!SNSUtil.isSNSPageShowing())&&SNSPageOpening){
							tempInfo = null;
							SNSPageOpening = false;
							if(mShareStateListener!=null&&!SNSUtil.isSNSStop()){
								mShareStateListener.shareAction(
										ShareStateListener.SHARE_FAILED,
										"网络超时,请稍后重试");
							}
							SNSUtil.stopSNS();
						}
						break;
		
					default:
						break;
					}
				}
		   };
	   }
	
	@Override
	public void setShareStateListener(ShareStateListener shareStateListener) {
		mShareStateListener = shareStateListener;
	}

	@Override
	public ShareStateListener getShareStateListener() {
		return mShareStateListener;
	}

	@Override
	public void shareMessage(ShareInfo shareInfo) {
		
		L.v(TAG, "shareMessage", "shareInfo : " + shareInfo);
		if(mShareStateListener!=null){
			mHandler.obtainMessage(ShareStateListener.SHARING, "sharing").sendToTarget();
		}
		if(shareInfo==null||TextUtils.isEmpty(shareInfo.text)){
			if(mShareStateListener!=null){
				mHandler.obtainMessage(ShareStateListener.SHARE_CANCEL, "分享失败").sendToTarget();
			}
			return;
		}
		switch (shareInfo.SNSType) {
			case SINA_WEIBO_TYPE:
				share2Sinawb(shareInfo);
				break;
			case TENCENT_QQ_TYPE:
				share2QZone(shareInfo);
				break;
			case TENCENT_WEIBO_TYPE:
				share2Tencentwb(shareInfo);
				break;
			case TENCENT_WEIXIN_TYPE:
				share2Weixin(shareInfo);
				break;
			case TENCENT_WEIXIN_FRIEND_TYPE:
				share2WeixinFriends(shareInfo);
				break;
	
			default:
				break;
		}
		
		tempInfo = shareInfo;
	}

	/**
	 * 分享到新浪微博
	 * @param shareInfo
	 */
	private void share2Sinawb(ShareInfo shareInfo){
		ShareParams sp = new ShareParams();
		
		if(TextUtils.isEmpty(shareInfo.imagePath)&&TextUtils.isEmpty(shareInfo.imageUrl)&&FoneUtil.isDefaultShareimageExists()){
			shareInfo.imagePath = ApplicationManage.getGlobalContext().getFilesDir()+ "/defaultImage.jpg";
		}
		
		sp.setText(shareInfo.text);
		sp.setImagePath(shareInfo.imagePath);
		sp.setImageUrl(shareInfo.imageUrl);
		sp.setSite(shareInfo.site);
		sp.setSiteUrl(shareInfo.siteUrl);
		
//		sp.setText("新浪微博分享测试");

		Platform platform = ShareSDK.getPlatform(mContext, SinaWeibo.NAME);
		
		if(mSNSShareManager.sinaLocalInfo!=null){
			platform = setValid(platform, mSNSShareManager.sinaLocalInfo);
		}
		platform.setPlatformActionListener(new MPlatformActionListener(SINA_WEIBO_TYPE));
		
		// 判断是否授权 授权是否有效   若没有授权或授权无效 打开授权页开关
		if(!platform.isValid()){
			MyAuthorizeAdapter.open=true;
			mHandler.removeMessages(STOP_SNS);
			mHandler.sendEmptyMessageDelayed(STOP_SNS, 10000l);
			SNSPageOpening = true;
		}
		platform.SSOSetting(true);
		platform.share(sp);
	}

	/**
	 * 分享到QQ空间
	 * @param shareInfo
	 */
	private void share2QZone(ShareInfo shareInfo){

		ShareParams sp = new ShareParams();
		
		sp.setTitle(shareInfo.title); 
		sp.setTitleUrl(shareInfo.titleUrl); // 标题的超链接 
		sp.setText(shareInfo.text); 
		sp.setSite(shareInfo.site);
		sp.setSiteUrl(shareInfo.siteUrl);
		sp.setImageUrl(shareInfo.imageUrl);
		
//		sp.setTitle("腾讯QQ空间分享测试"); 
//		sp.setTitleUrl("http://www.baidu.com"); // 标题的超链接 
//		sp.setText("腾讯QQ空间分享测试内容"); 
//		sp.setImageUrl("http://f1.sharesdk.cn/imgs/2014/02/26/owWpLZo_638x960.jpg");
//		sp.setSite("100tv");
//		sp.setSiteUrl("http://www.qq.com");
		
		Platform qzone = ShareSDK.getPlatform(mContext, QZone.NAME);
		
		
		// 打开QZone分享页开关
		MyQZoneWebShareAdapter.open = true;
		mHandler.removeMessages(STOP_SNS);
		mHandler.sendEmptyMessageDelayed(STOP_SNS, 10000l);
		SNSPageOpening = true;
		
		qzone.setPlatformActionListener (new MPlatformActionListener(TENCENT_QQ_TYPE)); // 设置分享事件回调 
		qzone.SSOSetting(true);
		qzone.share(sp);// 执行图文分享 
		
	}
	
	/**
	 * 分享到腾讯微博
	 * @param shareInfo
	 */
	private void share2Tencentwb(ShareInfo shareInfo){
		ShareParams sp = new ShareParams();
		
		if(TextUtils.isEmpty(shareInfo.imagePath)&&TextUtils.isEmpty(shareInfo.imageUrl)&&FoneUtil.isDefaultShareimageExists()){
			shareInfo.imagePath = ApplicationManage.getGlobalContext().getFilesDir()+ "/defaultImage.jpg";
		}
		
		sp.setText(shareInfo.text);
		if(shareInfo.imagePath!=null){
			sp.setImagePath(shareInfo.imagePath);
		}else if(shareInfo.imageUrl!=null){
			sp.setImagePath(shareInfo.imageUrl);
		}
		Platform platform = ShareSDK.getPlatform(mContext, TencentWeibo.NAME);
		
		if(mSNSShareManager.tencentLocalInfo!=null){
			platform = setValid(platform, mSNSShareManager.tencentLocalInfo);
		}
		platform.setPlatformActionListener(new MPlatformActionListener(TENCENT_WEIBO_TYPE));
		
		// 判断是否授权  若没有授权打开授权页开
		if(!platform.isValid()){
			MyAuthorizeAdapter.open=true;
			mHandler.removeMessages(STOP_SNS);
			mHandler.sendEmptyMessageDelayed(STOP_SNS, 10000l);
			SNSPageOpening = true;
		}
		platform.SSOSetting(true);
		platform.share(sp);
	}

	/**
	 * 分享到微信
	 * @param shareInfo
	 */
	private void share2Weixin(ShareInfo shareInfo){
//		ShareParams sp = new ShareParams();
//		
//		sp.setText(shareInfo.text);
//		sp.setImagePath(shareInfo.imagePath);
//		sp.setImageUrl(shareInfo.imageUrl);
//		
//		sp.setShareType(Wechat.SHARE_WEBPAGE);
//		sp.setTitle("微信测试title");
//		sp.setText("微信分享测试");
//		sp.setUrl("http://www.baidu.com");
//		sp.setImagePath("");
//		sp.setImageUrl("http://ww3.sinaimg.cn/bmiddle/64f9539ejw1ef56zm81pvj20qo0is75s.jpg");
//		
//		Platform platform = ShareSDK.getPlatform(mContext, Wechat.NAME);
//		platform.setPlatformActionListener(new MPlatformActionListener());
//		
//		platform.share(sp);
		
		WeiXinShareUtil.getInstance(mContext).shareMessage(shareInfo, mShareStateListener);
		
	}
	

	/**
	 * 分享到微信朋友圈
	 * @param shareInfo
	 */
	private void share2WeixinFriends(ShareInfo shareInfo){
//		ShareParams sp = new ShareParams();
//		
//		sp.setText(shareInfo.text);
//		sp.setImagePath(shareInfo.imagePath);
//		sp.setImageUrl(shareInfo.imageUrl);
//		
//		sp.setShareType(WechatMoments.SHARE_WEBPAGE);
//		sp.setTitle("微信朋友圈测试title");
//		sp.setText("微信朋友圈分享测试");
//		sp.setUrl("http://www.baidu.com");
//		sp.setImagePath("");
//		sp.setImageUrl("http://ww3.sinaimg.cn/bmiddle/64f9539ejw1ef56zm81pvj20qo0is75s.jpg");
//		
//		
//		Platform platform = ShareSDK.getPlatform(mContext, WechatMoments.NAME);
//		platform.setPlatformActionListener(new MPlatformActionListener());
//		platform.share(sp);
		
		WeiXinShareUtil.getInstance(mContext).shareMessage(shareInfo, mShareStateListener);
	}
	
	/**
	 * 获取用户信息
	 * @param platform
	 * @param res
	 * @return
	 */
	private SNSUserInfo getUserInfo(int type,Platform platform,HashMap<String, Object> res ){
		
		SNSUserInfo user = new SNSUserInfo();
		
		if(platform.isValid()){
			
			user.snsType = type;
			user.expiresIn = String.valueOf(platform.getDb().getExpiresIn());
			user.expiresTime = String.valueOf(platform.getDb().getExpiresTime());
			user.accessToken = platform.getDb().getToken();
			user.headPic = platform.getDb().getUserIcon();
			user.nickName = platform.getDb().getUserName();
			user.thirdPlatformID = platform.getDb().getUserId();
			
		}
		return user;
	}
	
	
	/**
	 * 用绑定SNS信息设置授权
	 * @param plat
	 */
	private Platform setValid(Platform plat,SNSUserInfo userInfo){
		try{
			if(plat!=null&&!plat.isValid()&&userInfo!=null&&!TextUtils.isEmpty(userInfo.accessToken)){
				
				long expiresTime = Long.valueOf(userInfo.expiresTime);
				long expiresIn = (expiresTime - System.currentTimeMillis())/1000;//计算出剩余的有效时间
				if(expiresIn<3600)//如果剩余有效时间小于1小时  则重新授权
					return plat;
				//TODO设置本地授权 
				PlatformDb db = plat.getDb();
				db.put("icon", userInfo.headPic);
				db.put("nickname", userInfo.nickName);
				db.putUserId(userInfo.thirdPlatformID);
				db.putExpiresIn(expiresIn);
				db.putToken(userInfo.accessToken);
			}
		}catch(Exception e){
			L.e(TAG, "setValid", e.getMessage());
		}
		return plat;
	}
	
	/**
	 * 分享是否已经授权
	 * @param type
	 * 			SNSShareManager.SINA_WEIBO_TYPE
	 * 			SNSShareManager.TENCENT_WEIBO_TYPE
	 * @return
	 */
	public boolean isAuthorized(int type){
		String fileName = null;
		switch (type) {
		case ISNSShareManager.SINA_WEIBO_TYPE:
			fileName = ISNSShareManager.SINA_WEIBO_LOCALSNSINFO;
			break;
		case ISNSShareManager.TENCENT_WEIBO_TYPE:
			fileName = ISNSShareManager.TENCENT_WEIBO_LOCALSNSINFO;
			break;
		}
		if(TextUtils.isEmpty(fileName)){
			return false;
		}
		return SerializationUtil.isExistDataCache(mContext, fileName);
	}
	
	/**
	 * 清除分享授权
	 * @param type
	 * @return
	 */
	public boolean removeAuthorizetion(int type){
		String fileName = null;
		switch (type) {
		case ISNSShareManager.SINA_WEIBO_TYPE:
			fileName = ISNSShareManager.SINA_WEIBO_LOCALSNSINFO;
			break;
		case ISNSShareManager.TENCENT_WEIBO_TYPE:
			fileName = ISNSShareManager.TENCENT_WEIBO_LOCALSNSINFO;
			break;
		}
		if(TextUtils.isEmpty(fileName)){
			return false;
		}
		SerializationUtil.removeSNSInfoSerialization(mContext, fileName);
		return SerializationUtil.isExistDataCache(mContext, fileName);
	}
	
	
	private class MPlatformActionListener implements PlatformActionListener {

		private int mtype = 0;
		
		public MPlatformActionListener(int type){
			super();
			mtype = type;
		}
		
		@Override
		public void onComplete(Platform platform, int action,HashMap<String, Object> res) {
			
			tempInfo = null;
			if(action == Platform.ACTION_SHARE){
				L.v(TAG, "onComplete", "share success");
				if(mShareStateListener!=null){
					if(SNSPageOpening&&((mtype==SINA_WEIBO_TYPE)||(mtype==TENCENT_WEIBO_TYPE))){
						SNSUserInfo userInfo = getUserInfo(mtype, platform, res);
						mHandler.obtainMessage(GET_USERINFO_SUCCESS, userInfo).sendToTarget();
					}
					mHandler.obtainMessage(ShareStateListener.SHARE_SUCCESS, "share success").sendToTarget();
				}
				platform.removeAccount();
				SNSPageOpening = false;
			}
		}
		
		@Override
		public void onCancel(Platform platform, int action) {
			tempInfo = null;
			if(action == Platform.ACTION_SHARE){
				SNSPageOpening = false;
				L.v(TAG, "onCancel", "share cancel");
				if(mShareStateListener!=null){
					mHandler.obtainMessage(ShareStateListener.SHARE_CANCEL, "share cancel").sendToTarget();
					platform.removeAccount();
				}
			}
		}

		@Override
		public void onError(Platform platform, int action, Throwable t) {
			String expName = t.getClass().getSimpleName();
			L.v(TAG, "onError", expName + " : " +t.getMessage());
			L.v(TAG, "onError", "action : " + action );
			try{
				if(platform.getName().equals(SinaWeibo.NAME)){//新浪微博分享出错
					JSONObject jsonObject = new JSONObject(t.getMessage());
					int code = jsonObject.getInt("error_code");
					switch (code) {
						case 21332://token 失效
						case 21314://token 已经被使用
						case 21315://token 已经过期
						case 21316://token 不合法
						case 21317://token 不合法
							removeAuthorizetion(SINA_WEIBO_TYPE);
							platform.removeAccount();
							SerializationUtil.removeSNSInfoSerialization(mContext, SINA_WEIBO_LOCALSNSINFO);
							sinaLocalInfo = null;
							if(tempInfo!=null){
								shareMessage(tempInfo);
								return;
							}
							break;
						default:
							break;
					}
				}
			}catch(Exception e){
				L.e(TAG, "onError", e.getMessage());
			}
			SNSPageOpening = false;
			if(mShareStateListener!=null){
				String errorInfo = "分享失败";
//				if ("WechatClientNotExistException".equals(expName)
//						|| "WechatTimelineNotSupportedException".equals(expName)
//						|| "WechatFavoriteNotSupportedException".equals(expName)) {
//					errorInfo = "目前您的微信版本过低或未安装微信，需要安装微信才能使用";
//				}
				mHandler.obtainMessage(ShareStateListener.SHARE_FAILED, errorInfo).sendToTarget();
			}
			platform.removeAccount();
		}
	}
}
